<?php

/**
 * -----------------------------------------------
 *  php-script_auto - Launcher in PHP-CLI Mode
 * -----------------------------------------------
 *  Auto Job Loader and Manager
 * 
 * @author $Author: damien.viguier@gmail.com $
 * @version $Revision: 9 $
 */
const APP_DIR_SEPERATOR = '/';


// Dependecies management
include_file('src/10_conf/global_constants.php');
include_file('src/main.php');

// Check PHP-CLI Mode
if (PHP_SAPI != "cli") {	
	echo "This script can be only invoked in PHP-CLI mode!";
	exit;
}

// Call functionality
global $l_as_mode;

/**
 * Check numbers and coherence of args
 */
function checkScriptArgs()
{
	global $l_as_mode;
	$l_b_valid = false;
	$l_b_validMsg = true;
	
	$l_as_mode = array();
	
	/** Check numbers of arguments **/
	if(is_int($_SERVER['argc']) && $_SERVER['argc']>1)
	{
		// Help Mode => main.php -h
		if(!$l_b_valid && is_int($_SERVER['argc']) && $_SERVER['argc']>1 && array_search("-h",$_SERVER['argv'],true)!=false)
		{
			echo "Syntax of command : main.php [-h]|[-l allfromjobs|jobName]|[-i jobName]|[-d]  \n";
			echo "---------------------------------------------------------- \n";
			echo " -> [-h] : Help Mode \n";
			echo " -> [-l] : load jobs in memory \n";
			echo " 			options: \n";
			echo "				allfromjobs	: Load all job from jobs subdirectory \n";
			echo "				jobName		: Load specific job from jobs subdirectory \n";
			echo "---------------------------------------------------------- \n";
			$l_b_validMsg = false;
		}
		
		// Dev Mode => main.php -d
		if(!$l_b_valid && is_int($_SERVER['argc']) && $_SERVER['argv']>1 && array_search("-d",$_SERVER['argv'],true)!=false)
		{
			echo "---------------------------------------------------------- \n";
			echo " DEV-MODE	\n";
			echo "---------------------------------------------------------- \n";
			$l_as_mode["development"] = true;
			$l_b_valid = true;
		}
		
		// Immediate Mode => main.php -i jobName
		// check  argv[2] value as existing item in 'jobs' subdirectory (argv[2] = jobs/argv[2].job.php)
		if(!$l_b_valid && is_int($_SERVER['argc']) && $_SERVER['argc']>2 && array_search("-i",$_SERVER['argv'],true)!=false)
		{
			$l_x_idxAction = intval(array_search("-i",$_SERVER['argv'],true));
			$l_x_idxExpectedJob = intval(array_search("-i",$_SERVER['argv'],true))+1;
			
			if( array_key_exists($l_x_idxAction,$_SERVER['argv']) && array_key_exists($l_x_idxExpectedJob,$_SERVER['argv']) &&
			 	 is_string($_SERVER['argv'][$l_x_idxExpectedJob]) )
			{
				echo "Immediate mode called on '".$_SERVER['argv'][$l_x_idxExpectedJob].".job.php' php job file.\n";
				$l_as_mode['immediateRun'] = $_SERVER['argv'][$l_x_idxExpectedJob];
				$l_b_valid = true;
			}
			else 
				echo "Second argument 'JobName' is missing.\n";
		}
	}
	else 
	{
		throw new Exception("Nombre d'argument invalide !");
	}
	
	// Invalid message
	if(!$l_b_valid && $l_b_validMsg)
	{
		echo "Syntax of command invalid! please use -h to see details\n";
	}
	
	// return validity status
	return $l_b_valid;
}

// Main function - launch action
function main($p_as_mode)
{
	try
	{
		JobsManager::initializeManager();
		
		if(array_key_exists("development", $p_as_mode))
		{
			//echo func_num_args();
			$l_o_job = new Job();
			$l_o_job->RunJob();
		}
		elseif (array_key_exists("immediateRun", $p_as_mode))
		{
			JobsManager::getLogManager()->setOutputStream("file", sprintf("logs/log-%s-JOB_%s.log",date("Ymd_h:i:s"),$p_as_mode["immediateRun"]));
			php_jobs_launcher::runJob($p_as_mode["immediateRun"]);
		}
		JobsManager::getLogManager()->flushNewLogsOnAllStream();
	}
	catch(Exception $e)
	{
		echo "Final Exception management";		
	}
}

function include_file($p_s_file)
{
	if(!ini_get('open_basedir') && !ini_get('safe_mode'))
	{
		include_once $p_s_file;
	}
	else 
	{
		ini_set("include_once", ini_get("include_once").":".$_SERVER['PWD']);
		include_once $_SERVER['PWD'].APP_DIR_SEPERATOR.$p_s_file;
	}
}

if(checkScriptArgs()) main($l_as_mode); else exit;


